<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar title="黑马头条-登陆" />
    <!-- 表单部分 -->
    <van-form ref="form">
      <van-field
         v-model="mobile"
         label="手机号"
         placeholder="请输入手机号"
         required
         :rules="[{required: true, validatorForMobile, message: '请输入手机号',trigger:'onBlur'}]"
       />
       <van-field
         v-model="code"
         label="密码"
         placeholder="请输入密码"
         required
         :rules="[{required: true, validatorForCode, message: '请输入密码',trigger:'onBlur'}]"
       />
     </van-form>
    <!-- 登陆按钮 -->
    <div class="btn-wrap">
      <van-button type="info" class="btn" @click="hLogin">登陆</van-button>
    </div>
  </div>
</template>

<script>
// 13912345678
// 246810
import { login } from '@/api/user.js'
export default {
  name: 'Login',
  data () {
    return {
      mobile: '13912345678',
      code: '246810'
    }
  },
  methods: {
    validatorForCode (val) {
      return val !== ''
    },
    // 验证手机号 返回值必须为true才能验证通过
    validatorForMobile (val) {
      return val !== ''
    },
    // 发送登录
    hLogin () {
      // 先校验 校验成功之后才可以登录
      this.$refs.form.validateAll().then(async () => {
        // res表示所有需要校验的表单项都通过校验时才为true，否则为false
        const res = await login(this.mobile, this.code)
        console.log(res)
        // 成功获得token之后通过提交mutation将token数据存入vuex (直接提交)
        this.$store.commit('setToken', res.data.data)
        this.$router.push('/')
      }).catch(() => {
        console.log('验证失败')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login {
    .btn-wrap {
      padding:20px;
      .btn {
        width: 100%;
        background-color: #6db4fb;
        color: #fff;
      }
    }
}
</style>
